package com.ruoyi.common.utils.hangxin;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.lang.reflect.Array;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.Map;
import java.util.regex.Pattern;

public class CommonUtil {
    static final Pattern SPECIAL_REGEX = Pattern.compile("\\s*|\t|\r|\n");
    static final Pattern QUERY_REGEX = Pattern.compile("[^'|‘\\x22]+");
    public static final Pattern PHONE_REGEX = Pattern.compile("^1[3-9][0-9]{9}$");

    /**
     * 判断对象是否为空
     *
     * @param obj 对象
     * @return {@code true}: 为空<br>{@code false}: 不为空
     */
    @SuppressWarnings("unchecked")
    public static boolean isEmpty(Object obj) {
        if (obj == null) {
            return true;
        }
        if (obj instanceof String && obj.toString().length() == 0) {
            return true;
        }
        if (obj.getClass().isArray() && Array.getLength(obj) == 0) {
            return true;
        }
        if (obj instanceof Collection && ((Collection) obj).isEmpty()) {
            return true;
        }
        if (obj instanceof Map && ((Map) obj).isEmpty()) {
            return true;
        }
        return false;
    }

    /**
     * 将InputStream转换为byte数组
     *
     * @param inputStream
     * @return
     * @throws IOException
     */
    public static byte[] read(InputStream inputStream) throws IOException {
        try {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int num = inputStream.read(buffer);
            while (num != -1) {
                baos.write(buffer, 0, num);
                num = inputStream.read(buffer);
            }
            baos.flush();
            return baos.toByteArray();
        } finally {
            if (inputStream != null) {
                inputStream.close();
            }
        }
    }

    /**
     * 判断对象是否非空
     *
     * @param obj 对象
     * @return {@code true}: 非空<br>{@code false}: 空
     */
    public static boolean isNotEmpty(Object obj) {
        return !isEmpty(obj);
    }

    //接口参数转化
    public static String urlencode(Map<String, Object> data) {
        //将map里的参数变成像 showapi_appid=###&showapi_sign=###&的样子
        StringBuilder sb = new StringBuilder();
        for (Map.Entry i : data.entrySet()) {
            try {
                sb.append(i.getKey()).append("=").append(URLEncoder.encode(i.getValue() + "", "UTF-8")).append("&");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
        return sb.toString();
    }

    //接口请求
    public static String httpRequest(String requestUrl, Map params) {
        //buffer用于接受返回的字符
        StringBuffer buffer = new StringBuffer();
        try {
            //建立URL，把请求地址给补全，其中urlencode（）方法用于把params里的参数给取出来
            URL url = new URL(requestUrl + "?" + urlencode(params));
            //打开http连接
            HttpURLConnection httpUrlConn = (HttpURLConnection) url.openConnection();
            httpUrlConn.setDoInput(true);
            httpUrlConn.setRequestMethod("GET");
            httpUrlConn.connect();

            //获得输入
            InputStream inputStream = httpUrlConn.getInputStream();
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);

            //将bufferReader的值给放到buffer里
            String str = null;
            while ((str = bufferedReader.readLine()) != null) {
                buffer.append(str);
            }
            //关闭bufferReader和输入流
            bufferedReader.close();
            inputStreamReader.close();
            inputStream.close();
            inputStream = null;
            //断开连接
            httpUrlConn.disconnect();

        } catch (Exception e) {
            e.printStackTrace();
        }
        //返回字符串
        return buffer.toString();
    }


    /**
     * 获取登录用户IP地址
     *
     * @param request
     * @return
     */
    public static String getIpAddr(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        if (ip.equals("0:0:0:0:0:0:0:1")) {
            ip = "本地";
        }
        return ip;
    }


    public static String doubleTrans(double d) {
        if (Math.round(d) - d == 0) {
            return String.valueOf((long) d);
        }
        return String.valueOf(d);
    }

    /**
     * 指定日期加上天数后的日期
     *
     * @param num      为增加的天数
     * @param currdate 创建时间
     * @return
     * @throws ParseException
     */
    public static Date plusDay(int num, Date currdate) throws ParseException {
        System.out.println("现在的日期是：" + currdate);
        Calendar ca = Calendar.getInstance();
        ca.add(Calendar.DATE, num);// num为增加的天数，可以改变的
        currdate = ca.getTime();
        System.out.println("增加天数以后的日期：" + currdate);
        return currdate;
    }

    /**
     * 当前日期加上天数后的日期
     *
     * @param num 为增加的天数
     * @return
     */
    public static String plusDay2(int num) {
        Date d = new Date();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String currdate = format.format(d);
        System.out.println("现在的日期是：" + currdate);

        Calendar ca = Calendar.getInstance();
        ca.add(Calendar.DATE, num);// num为增加的天数，可以改变的
        d = ca.getTime();
        String enddate = format.format(d);
        System.out.println("增加天数以后的日期：" + enddate);
        return enddate;
    }

    /**
     * 计算某个时间距离当前时间的天数,小时数以及分钟数.
     *
     * @param calDate
     * @return
     */
    public static String calculateTime(Date calDate) {
        String tips = "";
        Date now = new Date();
        long l = calDate.getTime() - now.getTime();
        long days = (l / (1000 * 60 * 60 * 24));
        if (days > 0) {
            tips += days;
        } else {
            tips = "0";
        }
//        long hours =  (l / (1000 * 60 * 60) - days*24);
//        if (hours > 0 || (days > 0 && hours == 0)){
//            tips += hours + "小时";
//        }
//        long mins =  (l / (1000 * 60)) - days*24*60 - hours*60;
//        tips += mins + "分钟";
        return tips;
    }

    /**
     * 比较时间大小;如果time1早于time2返回true，否则返回false
     */
    public static boolean compare(String time1, String time2) throws ParseException {
        //如果想比较日期则写成"yyyy-MM-dd"就可以了
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        //将字符串形式的时间转化为Date类型的时间
        Date a = sdf.parse(time1);
        Date b = sdf.parse(time2);
        //Date类的一个方法，如果a早于b返回true，否则返回false
//		if(a.before(b))
//			return true;
//		else
//			return false;
        /*
         * 如果你不喜欢用上面这个太流氓的方法，也可以根据将Date转换成毫秒*/
        if (a.getTime() - b.getTime() < 0)
            return true;
        else
            return false;

    }

    /**
     * 获取设备前缀，PC或phone
     * android : 所有android设备 mac os : iphone ipad windows
     * phone:Nokia等windows系统的手机
     *
     * @param request
     * @return
     */
    public static String getDevicePrefix(HttpServletRequest request) {
        String rs = "PC_";
        String requestHeader = request.getHeader("user-agent").toLowerCase();
        String[] deviceArray = new String[]{"android", "iphone", "ios", "windows phone", "micromessenger"};
        if (isNotEmpty(requestHeader)) {
            for (int i = 0; i < deviceArray.length; i++) {
                if (requestHeader.indexOf(deviceArray[i]) > 0) {
                    rs = "PHONE_";
                    break;
                }
            }
        }
        return rs;
    }

    /**
     * 格式化当前时间
     *
     * @param pattern
     * @return
     */
    public static String getNowTime(String pattern) {
        LocalDateTime now = LocalDateTime.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern(pattern);
        return now.format(formatter);
    }

    /**
     * 格式化当前时间
     *
     * @param pattern
     * @return
     */
    public static Date formatterStrToDate(String time, String pattern) throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat(pattern);
        //将字符串形式的时间转化为Date类型的时间
        return sdf.parse(time);
    }

    public static String replaceX(String str) {
        if (isEmpty(str)) {
            return "";
        } else {
            return SPECIAL_REGEX.matcher(str).replaceAll("");
        }
    }


}
